<?php
/**
 * 享元模式
 * Created by PhpStorm.
 * User: tangzhou
 * Date: 16-9-1
 * Time: 下午10:42
 */

/**
 * 所有享元父接口角色
 * Interface IBlogMode
 */
interface IBlogModel
{
    function showTime();
    function showColor();
}

class TangBlog implements IBlogModel
{
    function showTime()
    {
        echo "5点";
    }

    function showColor()
    {
        echo "黄色";
    }
}

class LeiBlog implements IBlogModel
{
    function showTime()
    {
        echo "6点";
    }

    function showColor()
    {
        echo "绿色";
    }
}

/**
 * 享元工厂
 * Class BlogFactory
 */
class BlogFactory
{
    private $model = array();

    function getBlog($name)
    {
        if (isset($this->model[$name])) {
            echo "我是缓存";
            return $this->model[$name];
        } else {
            try {
                echo "我是新建";
                $class = new ReflectionClass($name);
                $this->model[$name] = $class->newInstance();
                return $this->model[$name];
            }catch (\ReflectionException $e){
                echo "创建失败";
                return null;
            }
        }
    }
}

$bf=  new BlogFactory();
$tang = $bf->getBlog("TangBlog");
if (!empty($tang)) {
    $tang->showTime();
    $tang->showColor();
}

$tang = $bf->getBlog("TangBlog");
if (!empty($tang)) {
    $tang->showTime();
    $tang->showColor();
}

$xx = $bf->getBlog("xxx");
if (!empty($xx)) {
    $xx->showTime();
    $xx->showColor();
}